import type { RouteRecordRaw } from 'vue-router';

import { layoutStore } from '@/store/menu';
import { getAdminToken } from '@/utils/setToken';

import router from './router';

router.beforeEach((to, from, next) => {
  const store = layoutStore()
    if (to.meta?.title) {
        store.updatePageTitle(to.meta?.title)
    }
    store.updateCurrentPath(to.path)
  // console.log(router.getRoutes())
  if (to.path === '/' || to.path === '/404' || to.path.indexOf('authPlatform') === -1) { // 静态地址直接跳转
    next()
  } else {
    // console.log(store.getMenu())
    // console.log(store.getRoutesData(store.getMenu(),''))
    let Routerdata:any
    if(getAdminToken()) {
      if (store.menuData.length > 0) {
        next()
      } else {
        Routerdata = store.getRouter()
        const hasRoute = router.hasRoute(to.name!)
        // debugger
        Routerdata.forEach((item: RouteRecordRaw) => {
          router.addRoute('authAppHome', item)
        })
        // console.log(to)
        // console.log(router.hasRoute(to.name!))
       if(hasRoute) {
        next()
       }else{
        next({ ...to, replace: true })
       }
        return
      }
    } else {
      next('/')
    }
    
  }
})
export default router